package com.efounder.frame.tabbar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import java.util.List;

public class TabBarGradient extends HorizontalScrollView {
	private static final String TAG = "TabBar";
	
	//data
	/** 数据 **/
	private List<TabBarItemGradient> tabBarItems;
	/** 点击tab的监听 **/
	private OnTabBarItemClickListener onTabBarItemClickListener;
	
	//TabBar style
	private ViewGroup.LayoutParams params;
	private LinearLayout tabsContainer;
	/** 是否展开 **/
	private boolean shouldExpand = true;//
	
	//Item style
	private LinearLayout.LayoutParams shrinkTabLayoutParams;
	private LinearLayout.LayoutParams expandedTabLayoutParams;
	private int tabPadding = 0;
	/** 默认颜色 **/
	private int tabColor = 0xFFFF0000;
	/** 选中颜色 **/
	private int tabSelectedColor = 0xFF00FF00;
	/** 字体大小 **/
	private int tabTextSize = 15;
	/** tab背景颜色 **/
	private int tabBackgroundColor = 0x00FFFFFF;//默认透明
	
	private int selectedPosition = -1;
	
	/**是否更新ui的线程准备运行（保证updateTabStyles方法只运行一次,避免连续执行）**/
	private boolean updateStyleThreadIsReadyRun = false;
	
	
	private int indicatorTextColor = Color.BLACK;
	private int indicatorBackgroundColor = Color.RED;
	private int indicatorTextSize = 11;
	
	//test
	private int count = 0;
	
	
	public TabBarGradient(Context context, List<TabBarItemGradient> tabBarItems) {
		this(context, null,tabBarItems);
	}
	
	public TabBarGradient(Context context, ViewGroup.LayoutParams params, List<TabBarItemGradient> tabBarItems) {
		super(context);
		this.tabBarItems = tabBarItems;
		
		//设置可拉伸
		setFillViewport(true);
		//隐藏滚动条
		setHorizontalScrollBarEnabled(false);
		if (params == null) {
			int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 49, getResources().getDisplayMetrics());
			this.params = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, height);
		}else {
			this.params = params;
		}
		setLayoutParams(this.params);
		
		tabsContainer = new LinearLayout(context);
		tabsContainer.setPadding(0, 2, 0, 2);
		tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
		tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		
		shrinkTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
		expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);
		
		addView(tabsContainer);
		
		if (tabBarItems != null) {
			notifyDataSetChanged();
		}
		
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		Log.i(TAG, "-----onDraw");
		super.onDraw(canvas);
	}
	
	@Override
	protected void dispatchDraw(Canvas canvas) {
		Log.i(TAG, "-----dispatchDraw");
		super.dispatchDraw(canvas);
	}
	
	/**
	 * tabBarItems 数据发生变化时调用此方法，根据数据重新布置界面
	 */
	public void notifyDataSetChanged(){
		tabsContainer.removeAllViews();
		for (int i = 0; i < tabBarItems.size(); i++) {
			TabBarItemGradient tabBarItem = tabBarItems.get(i);
			addTab(i, tabBarItem);
		}
//		updateTabStyles();
		postUpdateTabStyles();
	}
	
	
	
	private void addTab(final int position, TabBarItemGradient tabBarItem) {
		tabBarItem.setFocusable(false);
		tabBarItem.setFocusableInTouchMode(false);
		tabBarItem.setTabColor(tabColor);
		tabBarItem.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i(TAG, "-----onClick");
				if (position != selectedPosition) {
					onSelectedTab(position);
					
					if (onTabBarItemClickListener != null) {
						onTabBarItemClickListener.onTabBarItemClick((TabBarItemGradient)v, position);
					}
				}
			}
		});
		
		tabsContainer.addView(tabBarItem, position, shouldExpand ? expandedTabLayoutParams : shrinkTabLayoutParams);
	}
	
	/**
	 * 获取某个位置的 TabBarItemGradient
	 * @param position
	 * @return
	 */
	public TabBarItemGradient getTabBarItem(int position){
		return (TabBarItemGradient)tabsContainer.getChildAt(position);
	}
	
	
	/**
	 * 设置被选中的tab
	 * @param position
	 */
	public void setSelectedTab(int position){
		this.selectedPosition = position;
		postUpdateTabStyles();
	}
	
	private void onSelectedTab(int position){
		//在updateStyle之后调用此方法
		Log.i(TAG, "------onSelectedTab 执行--position:" + position);
		if (selectedPosition != -1 && selectedPosition != position) {
			TabBarItemGradient agoSelectedSTabBarItem = tabBarItems.get(selectedPosition);
			//XXX
//			agoSelectedSTabBarItem.setTabColor(tabColor);
			agoSelectedSTabBarItem.setTabAlpha(0f);
			selectedPosition = position;
		}
		TabBarItemGradient tabBarItem = tabBarItems.get(position);
//		tabBarItem.setTabSelectedColor(tabSelectedColor);
		tabBarItem.setTabAlpha(1f);
//		//请求焦点
//		boolean isFocus= tabBarItem.requestFocus();
//		Log.i(TAG, "-----请求焦点:" + isFocus);
		int x = tabBarItem.getLeft() + tabBarItem.getWidth()/2 - getWidth()/2;
		smoothScrollTo(x, 0);
	}
	
	private void postUpdateTabStyles() {
		Log.i(TAG, "-----是否更新ui的线程准备运行:" + updateStyleThreadIsReadyRun);
		if (!updateStyleThreadIsReadyRun) {
			updateStyleThreadIsReadyRun = true;
			post(new Runnable() {
				
				@Override
				public void run() {
					updateTabStyles();
				}
			});
		}
		
	}
	
	private void updateTabStyles() {

		Log.i(TAG, "-----updateTabStyles执行次数:" + (++count));
		for (int i = 0; i < tabBarItems.size(); i++) {
			TabBarItemGradient tabBarItem = tabBarItems.get(i);
			tabBarItem.setPadding(tabPadding, 0, tabPadding, 0);
			
			//XXX 颜色是初始化用的，改变颜色用alpha
			tabBarItem.setTabColor(tabColor);
			tabBarItem.setTabSelectedColor(tabSelectedColor);
			
			tabBarItem.setTabTextSize(tabTextSize);
			int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, getResources().getDisplayMetrics());
			tabBarItem.setPadding(padding, 0, padding, 0);
			tabBarItem.setBackgroundColor(tabBackgroundColor);
			
			tabBarItem.setIndicatorTextColor(indicatorTextColor);
			tabBarItem.setIndicatorTextSize(indicatorTextSize);
			tabBarItem.setIndicatorBackgroundColor(indicatorBackgroundColor);
		}
		
		if (selectedPosition == -1) {
			onSelectedTab(0);
		}else {
			onSelectedTab(selectedPosition);
		}
		
		//更新UI完毕，设置为false
		updateStyleThreadIsReadyRun = false;
	
	}
	
	public boolean isShouldExpand() {
		return shouldExpand;
	}

	/**
	 * 设置是否展开，对于Tab不能占满屏幕的情况，设置展开可以使其占满，默认true（占满）
	 * @param shouldExpand 
	 */
	public void setShouldExpand(boolean shouldExpand) {
		this.shouldExpand = shouldExpand;
	}

	/**
	 * 设置TabBarItem点击事件
	 * @param onTabBarItemClickListener
	 */
	public void setOnTabBarItemClickListener(OnTabBarItemClickListener onTabBarItemClickListener) {
		this.onTabBarItemClickListener = onTabBarItemClickListener;
	}
	
	/**
	 * 获取所有TabBarItem
	 * @return
	 */
	public List<TabBarItemGradient> getTabBarItems() {
		return tabBarItems;
	}

	/**
	 * 设置TabBarItem
	 * @param tabBarItems
	 */
	public void setTabBarItems(List<TabBarItemGradient> tabBarItems) {
		this.tabBarItems = tabBarItems;
		notifyDataSetChanged();
	}
	
	
	/**
	 * 获取tab间距
	 * @return 单位：dip
	 */
	public int getTabPadding() {
		return tabPadding;
	}

	/**
	 * 设置tab间距
	 * @param tabPadding 单位：dip
	 */
	public void setTabPadding(int tabPadding) {
		this.tabPadding = tabPadding;
		postUpdateTabStyles();
	}

	/**
	 * 获取Tab图片和文字的颜色
	 */
	public int getTabColor() {
		return tabColor;
	}

	/**
	 * 设置Tab图片和文字的默认颜色
	 * @param tabColor
	 */
	public void setTabColor(int tabColor) {
		this.tabColor = tabColor;
		postUpdateTabStyles();
	}

	/**
	 * 获取Tab选中时的颜色
	 * @return
	 */
	public int getTabSelectedColor() {
		return tabSelectedColor;
	}

	/**
	 * 设置Tab选中时的颜色
	 * @param tabSelectedColor
	 */
	public void setTabSelectedColor(int tabSelectedColor) {
		this.tabSelectedColor = tabSelectedColor;
		postUpdateTabStyles();
	}

	
	public int getTabBackgroundColor() {
		return tabBackgroundColor;
	}

	public void setTabBackgroundColor(int tabBackgroundColor) {
		this.tabBackgroundColor = tabBackgroundColor;
		postUpdateTabStyles();
	}

	/**
	 * 获取Tab的文本大小
	 * @return
	 */
	public int getTabTextSize() {
		return tabTextSize;
	}

	/**
	 * 设置Tab的文本大小
	 * @param tabTextSize
	 */
	public void setTabTextSize(int tabTextSize) {
		this.tabTextSize = tabTextSize;
		postUpdateTabStyles();
	}

	
	
	/**
	 * 设置指示器（右上角小圆圈）数值
	 * @param position 指示器位置
	 * @param setIndicatorNumber 指示器数值
	 */
	public void setIndicatorNumber(int position,int setIndicatorNumber){
		getTabBarItem(position).setIndicatorNumber(setIndicatorNumber);
	}
	
	/**
	 * 清除某个位置上的指示器（右上角小圆圈） 
	 * @param position
	 */
	public void clearIndicator(int position){
		getTabBarItem(position).clearIndicator();
	}
	
	/**
	 * 清除所有指示器（右上角小圆圈）
	 */
	public void clearAllIndicator(){
		for (int i = 0; i < tabsContainer.getChildCount(); i++) {
			clearIndicator(i);
		}
	}
	
	/**
	 * 获取指示器（右上角小圆圈）文本颜色
	 * @return
	 */
	public int getIndicatorTextColor() {
		return indicatorTextColor;
	}

	/**
	 * 设置指示器（右上角小圆圈）文本颜色
	 * @param indicatorTextColor
	 */
	public void setIndicatorTextColor(int indicatorTextColor) {
		this.indicatorTextColor = indicatorTextColor;
		postUpdateTabStyles();
	}

	/**
	 * 获取指示器（右上角小圆圈）背景颜色
	 * @return
	 */
	public int getIndicatorBackgroundColor() {
		return indicatorBackgroundColor;
	}

	/**
	 * 设置指示器（右上角小圆圈）背景颜色
	 * @param indicatorBackgroundColor
	 */
	public void setIndicatorBackgroundColor(int indicatorBackgroundColor) {
		this.indicatorBackgroundColor = indicatorBackgroundColor;
		postUpdateTabStyles();
	}

	/**
	 * 获取指示器（右上角小圆圈）文本大小
	 * @return
	 */
	public int getIndicatorTextSize() {
		return indicatorTextSize;
	}

	/**
	 * 设置指示器（右上角小圆圈）文本大小
	 * @param indicatorTextSize
	 */
	public void setIndicatorTextSize(int indicatorTextSize) {
		this.indicatorTextSize = indicatorTextSize;
		postUpdateTabStyles();
	}

	

//	public void setTabAlpha(int position,float tabAlpha) {
//		TabBarItemGradient tabBarItem = getTabBarItem(position);
//		if (position == selectedPosition) {
//			tabBarItem.setTabAlpha(tabSelectedColor, tabAlpha);
//		}else {
//			tabBarItem.setTabAlpha(tabColor, tabAlpha);
//		}
//	}


	/**
	 * 点击tab时的监听
	 * @author hudq
	 *
	 */
	public interface OnTabBarItemClickListener{
		public void onTabBarItemClick(TabBarItemGradient tabBarItem, int position);
	}
	
}
